<?php
require_once "BaseAction.php";

require_once 'lib/thrift/client/VideoService.php';
require_once 'lib/thrift/client/MusicService.php';
require_once 'lib/thrift/client/PhotoService.php';
require_once 'lib/thrift/client/BlogService.php';

class Event_EventController extends TTEvent_Base_Action 
{
	
	public function init(){
		parent::init();
		$this->_helper->layout->setLayout('event');
	}
	
	public function indexAction() 
	{
		$this->_helper->eventCommon->buildMainMenuBlock(0);
		$this->setTitle('Mạng xã hội chia sẻ video video, download video, video phim, movie trailers, kết bạn, làm quen');
		
		
		//-----------------
		$this->view->banners = $this->_helper->eventCommon->getBanner('my');
		
		$eventModel = $this->loadModel('Event');
		$hotList = $eventModel->getMyEventList();
		
		$this->view->myList = $myEventList;
		
		$this->_helper->eventCommon->buildHtmlEventLeftMenu('detail', $this->owner_user->uid, $cmdIdx, $catId, $this->is_owner);
		
	}
	
	public function editAction(){
		                
		$eid = (int)$this->_getParam('eid', 0);
		$err = $this->checkEventEditPrivacy($eid);
		if(count($err) > 0){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}
		
		$user = $this->getUser();
		if(!$user->uid)
			$this->requireLogin();
		
		$networkList = $this->_helper->network->getUserNetworks($user->uid);
		if(!is_array($networkList) || count($networkList)<=0){
			$this->view->message = "Bạn phải gia nhập một cộng đồng thì mới có quyền tạo sự kiện! Quay về <a href=\"/event\"><strong>trang chủ</strong></a>";
			$this->_helper->layout->setLayout('event-home');
			$this->render("alert");
			return;
		}
		
		$req = $this->getRequest();
		$event = null;
		$err = array();
        
        //va         
        if(!$req->isPost()){
                    if(empty($event)){
            if($eid){      
                $event = $this->_helper->modelLoader->getEventInfo($eid);    
            }
            if(empty($event))
                $event = $this->makeDefaultEvent();
        }
        }                             
     //   $this->view->end_time_promote=$event->end_time_promote;
        $eventModel = $this->loadModel('Event'); 
      //  $end_time_promote_in_db=$eventModel->getEndTimePromote($eid);
        $end_time_promote_in_db=$event->end_time_promote;
        $this->view->end_time_promote_in_db=$end_time_promote_in_db;
       // $promote=$eventModel->getPromote($eid);
        //$promote=$event->promote;
      //  $this->view->promote=$promote;
        
     //   $check=$this->_getParam('check'); 
        
        $time_promote=$this->_getParam('time_promote');
        $this->view->time_promote=$time_promote;


        
        $unit_price=5000;
        $this->view->unit_price=$unit_price;
        
        $quantity=$time_promote*$unit_price;
        $this->view->quantity=$quantity;
        $end_time_promote=$time_promote*24*60*60;
        $timestamp=time();
        

        $tcoin=$eventModel->getTcoin($user->uid); 
        $this->view->tcoin=$tcoin;
        
 
        $this->view->zzz=$tcoin-$quantity;
        if(floor($tcoin/$unit_price)==0)
        {
            if(!$tcoin>0)
            $tcoin=0;
            $this->view->err_tcoin="Lưu ý :Bạn không đủ tcoin . Hiện bạn có ".$tcoin." tcoin ";
        }
               
        //va        
        
		if($req->isPost()){
			$event = $this->getPostEventObject($req);
           // print_r($event);
			$err = $this->checkEventInfo($event);
			if(count($err)==0){
				$err = $this->checkEventEditPrivacy($event->eid);
		
         
				if(count($err)==0){  
                   //va{
                    if($event->access==3){     
                        $cost=(int)$this->_getParam('cost');
                        $limit=(int)$this->_getParam('limit');
                        if($cost>0){
                        $eventModel->changeCostEventTicket($event->eid,$cost,$limit);      
                    }else{
                        $event->access=0;    
                    }                                                                       
                    }  
                   //va}          
					$eid = $this->saveEvent($event);
					$this->_helper->modelLoader->getEventInfo($eid, false, false);
					$this->_helper->eventCommon->cleanUserEventCache($eid, $user->uid, 0, EVENT_USER_STATUS_MEMBER);
					$note = '<a href="' . $this->view->url(array('eid' => $eid), 'event_detail') . '">' . htmlspecialchars($event->event_name) . '</a><br />';
                    $this->addModLog($user->uid, EVENT_WD_EDIT, $eid, $note);
                    
                    //va  mua hien thi trang chu{
                         if($time_promote>0 && $eid>0 && $time_promote>0)
                                {
                                    if($end_time_promote_in_db>time())
                                        {
                                        $end_time_promote=$end_time_promote_in_db+$end_time_promote;
                                        $eventModel->setEndTimePromote($eid,$end_time_promote);
                                        $eventModel->updateTcoin($user->uid,$quantity); 
                                        $eventModel->update_tt_tcoin_log($user->uid,$eid,$timestamp,$unit_price,$quantity);  
                                        $eventModel->update_total_tcoin($eid,$quantity);
                                        }
                                    else
                                        {
                                        $end_time_promote=$end_time_promote+time();
                                        $eventModel->setEndTimePromote($eid,$end_time_promote);
                                        $eventModel->updateTcoin($user->uid,$quantity);
                                        $eventModel->update_tt_tcoin_log($user->uid,$eid,$timestamp,$unit_price,$quantity);    
                                        $eventModel->update_total_tcoin($eid,$quantity);   
                                        }
                                }
                        //        if($eid>0){
                                     //   if($promote==0){
                                          //  $promote=EVENT_PROMOTE_VIP;
                                    //    }
                                     /*   if($check)
                                            {
                                                if($promote==0 && $end_time_promote_in_db > time()){
                                                    $promote=EVENT_PROMOTE_VIP;
                                                }
                                                $eventModel->changePromote2($eid,abs($promote));
                                            }
                                        else
                                            {
                                                $eventModel->changePromote2($eid,-1*abs($promote));  
                                            }   */
                               // }
     
                    //va  }
					$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/edit/picture/'.$eid);
                    
                }
				}
				else{
					//var_dump(array($err,$event));exit();
				}   
			}
			else{
				//var_dump($err);exit();
			}
		
		
	/*	if(empty($event)){
			if($eid){      
				$event = $this->_helper->modelLoader->getEventInfo($eid);    
			}
			if(empty($event))
				$event = $this->makeDefaultEvent();
		}     */
		                      
		$this->_helper->eventCommon->buildMainMenuBlock(4);
		$this->_helper->layout->setLayout('event-edit');
        $this->setTitle("Sửa: ".$event->event_name);
		
		$network_networkModel = $this->loadModel('Network', 'network');
		$ccdArr = $this->getCountryCityDistrict($event->country, $event->city, $event->district);
	/*va	
		$this->view->action = 'info';
		$this->view->networkList = $this->_helper->network->getUserNetworks($user->uid);
	*/	
		$this->view->categoryList = $this->_helper->eventCommon->getEventCategories();
		$this->view->ccd_s = $this->view->partial('event/area-select.phtml', $ccdArr);
		
		$this->view->event = $event;
		$this->view->errors = $err;      
       //va
        if($event->network_id>0){
            $this->view->network_name=$eventModel->getNetworkName($event->network_id);
        }
    /*    if($event->access==3){
            $this->view->eventTicket=$eventModel->getEventTicket($eid);
            
        } */
        //va
        
		
	}
	
	public function pictureAction(){
		$eid = (int)$this->_getParam('eid', 0);
		$err = $this->checkEventEditPrivacy($eid);
		
		if(count($err) > 0){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}
		
		$this->_helper->eventCommon->buildMainMenuBlock();
		$this->_helper->layout->setLayout('event-edit');
		
		$user = $this->getUser();
		if(!$user->uid)
			$this->requireLogin();
		
		$eid = $this->_getParam('eid', 0);
		$eid=(int)$eid;
		if(!$eid)
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event');
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		if(empty($event))
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event');
		
        $this->setTitle("Sửa logo: ".$event->event_name);
		$err = array();
		$req = $this->getRequest();
		
		$dateStr = date("Y/m/d", $event->created);	
		//$user_dir='/images/events/' . $dateStr . "/".$eid."/";
		$user_dir='/files/events/' . $dateStr . "/".$eid."/";
		if ($req->isPost())
		{
			$remove = $req->getQuery('remove');
			$eventModel = $this->loadModel('Event');
			$eventChanged = false;
			if ($remove==1){
				$setstr = "";
				$setArr = array();
				if(isset($_POST['logo']) ){
					$setstr = "logo=''";
					$setArr['logo'] = '';
				}
				if(isset($_POST['banner']) ){
					$setstr = ($setstr!=""?",":"")."banner=''";
					$setArr['banner'] = '';
				}
				if(count($setArr) > 0){
					$eventModel->update($setArr, 'eid='.$eid);
					$eventChanged = true;  
				}
				
			}
			else{
				if (is_uploaded_file($_FILES['event_pic']['tmp_name']))
				{
		
					if ($_FILES['event_pic']['size']>5*1024*1024)
					{
						return "";
					}
					$t = time();
					$t_hex = sprintf("%08x_", $t);
					$pic_name=$t_hex . strtolower($_FILES['event_pic']['name']);
					
					$pic_name = eventImageNormalizeFilename($pic_name);
					
					//check extension
					$arr=explode('.', $pic_name);
					if (empty($arr))
					{
						return "";
					}
					
					$ext=$arr[count($arr)-1];
					if ($ext!='jpg' && $ext !='jpeg' && $ext!='gif' && $ext !='png')
					{
						return "";
					}
					
					$path = EVENT_IMG_DIR . $user_dir;
					//make sure directory is already created
					
					if (!is_dir($path))
					{
						@mkdir($path, 0775, true);
					}
		
					//move to event dir
					move_uploaded_file($_FILES['event_pic']['tmp_name'], $path . $pic_name);
					$thumb_file=$t_hex . $eid . ".$ext";
					//$rs=image_scale($path . $pic_name, $path . $thumb_file, 200, 200);
					
					//$sql="UPDATE {mytt_event} SET logo='%s' WHERE eid=%d";
					//if($rs)
						//db_query($sql, $user_dir . $thumb_file, $eid);
					//else
						//db_query($sql, $user_dir . $pic_name, $eid);
					
					$eventModel->update(array('logo'=>$user_dir . $pic_name, 'image_server'=>EVENT_IMG_SERVER2), 'eid='.$eid);
					$eventChanged = true;
				}
				
				if (is_uploaded_file($_FILES['event_banner']['tmp_name']))
				{
		
					if ($_FILES['event_banner']['size']>5*1024*1024)
					{
						return "";
					}
					$t = time();
					$t_hex = sprintf("%08x_", $t);
					$banner_name=$t_hex . strtolower($_FILES['event_banner']['name']);
					
					$banner_name=eventImageNormalizeFilename($banner_name);
					
					//check extension
					$arr=explode('.', $banner_name);
					if (empty($arr))
					{
						return "";
					}
					
					$ext=$arr[count($arr)-1];
					if ($ext!='jpg' && $ext !='jpeg' && $ext!='gif' && $ext !='png')
					{
						return "";
					}
					
					$path=EVENT_IMG_DIR . $user_dir;
					//make sure directory is already created
					if (!is_dir($path))
					{
						@mkdir($path, 0775, true);
					}
		
					//move to event dir
					move_uploaded_file($_FILES['event_banner']['tmp_name'], $path . $banner_name);
					//$thumb_file=$t_hex . $eid."_banner" . ".$ext";
					//$rs=image_scale($path . $banner_name, $path . $thumb_file, 300, 300);
					
					//$sql="UPDATE {mytt_event} SET banner='%s',  banner_thumb='%s' WHERE eid=%d";
					
					//if($rs)
					//	db_query($sql, $user_dir . $banner_name, $user_dir . $thumb_file, $eid);
					//else
					//	db_query($sql, $user_dir . $banner_name, $user_dir . $banner_name, $eid);
					
					$eventModel->update(array('banner'=>$user_dir . $banner_name, 'banner_thumb'=>$user_dir . $banner_name, 'image_server'=>EVENT_IMG_SERVER2), 'eid='.$eid);
					$eventChanged = true;
				}
				
			}
			if($eventChanged){
				$event = $this->_helper->modelLoader->getEventInfo($eid, false, false);
				$this->_helper->eventCommon->cleanUserEventCache($eid, $user->uid, 0, EVENT_USER_STATUS_MEMBER);
				
				$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/edit/picture/'.$eid);
			}
		}
		
		$this->view->action = 'picture';
		$this->view->event = $event;
	}
	
	
	
	public function getCountryCityDistrict($countryid=0, $cityid=0, $districtid=0){
		// Init variables
		$rowNational = array();
		$rowNational[0] = "Quốc Gia";
	 	
		// get list of national
		$nationalModel = $this->loadModel('National');
		$national = $nationalModel->getAllNational();
		if ($national)
			foreach ($national as $nt_arr)
				$rowNational[$nt_arr->nid] = $nt_arr->name;
		
		$rowCity = array();
		$rowCity[0] = "Tỉnh/Thành phố";	
		if ($countryid)
		{
			// get list of city
			$cityModel = $this->loadModel('City');
			$city = $cityModel->getAllCity($countryid);
			if (!empty($city))
				foreach ($city as $nt_arr)
					$rowCity[$nt_arr->cid] = $nt_arr->name;		
		}
		
		$rowDistrict = array();
		$rowDistrict[0] = "Quận/Huyện";	
		if ($cityid)
		{
			// get list of district
			$districtModel = $this->loadModel('District');
			$district = $districtModel->getAllDistrict($cityid);
			if ($district)
				foreach ($district as $nt_arr)
					$rowDistrict[$nt_arr->did] = $nt_arr->name;		
		}
		
		// assign list
		$assign_list["rowNational"] = $rowNational;
		$assign_list["rowCity"] = $rowCity;
		$assign_list["rowDistrict"] = $rowDistrict;
		$assign_list["countryid"] = $countryid;
		$assign_list["cityid"] = $cityid;
		$assign_list["districtid"] = $districtid;
		return $assign_list;
	}
	
	public function getPostEventObject($req){
		$ret = new stdClass();
		$ret->eid = (int)$req->getPost('eid');
		
		$ret->event_name= trim($req->getPost("event_name"));
		$ret->network_id=$req->getPost("network_id");
		$ret->description=$req->getPost("description");
		$ret->cid=$req->getPost("cid");
		$ret->start_time = strtotime($req->getPost("start_time_year")."/".str_pad($req->getPost("start_time_month"), 2, "0", STR_PAD_LEFT)."/".str_pad($req->getPost("start_time_day"), 2, "0", STR_PAD_LEFT)." ".str_pad($req->getPost("start_time_hour"), 2, "0", STR_PAD_LEFT).":".str_pad($req->getPost("start_time_minute"), 2, "0", STR_PAD_LEFT));
		$ret->end_time = strtotime($req->getPost("end_time_year")."/".str_pad($req->getPost("end_time_month"), 2, "0", STR_PAD_LEFT)."/".str_pad($req->getPost("end_time_day"), 2, "0", STR_PAD_LEFT)." ".str_pad($req->getPost("end_time_hour"), 2, "0", STR_PAD_LEFT).":".str_pad($req->getPost("end_time_minute"), 2, "0", STR_PAD_LEFT));
		$ret->phone=$req->getPost("phone");
		$ret->key_word=$req->getPost("key_word");
		$ret->slogan=$req->getPost("slogan");
		
		$ret->address=$req->getPost("address");
		$ret->country=$req->getPost("national");
		$ret->city=$req->getPost("city");
		$ret->district=$req->getPost("district");
		$ret->website=$req->getPost("website");
		$ret->email=$req->getPost("email");

		//$ret->public=(int)$req->getPost("enable_public");
        $ret->public=0;
		
		// Forum
		$ret->forum=(int)$req->getPost("enable_forum");
		if ($ret->forum==1)
		{
			$privacy=(int)$req->getPost("forum_privacy");
			if ($privacy==0)
			{
				$ret->forum=0;
			}
			else
			{
				$ret->forum=1;
			}
		}
		else
		{
			$ret->forum=-1;
		}
		
		// Wall
		$ret->comment=(int)$req->getPost("enable_comment");
		if ($ret->comment==1)
		{
			$privacy=(int)$req->getPost("comment_privacy");
			if ($privacy==0)
			{
				$ret->comment=0;
			}
			else if ($privacy==2)
			{
				$ret->comment=2;
			}
			else
			{
				$ret->comment=1;
			}
		}
		else
		{
			$ret->comment=-1;
		}
		
		// Website
		$ret->bookmark=(int)$req->getPost("enable_bookmark");
		if ($ret->bookmark==1)
		{
			$privacy=(int)$req->getPost("bookmark_privacy");
			if ($privacy==0)
			{
				$ret->bookmark=0;
			}
			else
			{
				$ret->bookmark=1;
			}
		}
		else
		{
			$ret->bookmark=-1;
		}
		
		// Clip
		$ret->video=(int)$req->getPost("enable_video");
		if ($ret->video==1)
		{
			$privacy=(int)$req->getPost("video_privacy");
			if ($privacy==0)
			{
				$ret->video=0;
			}
			else
			{
				$ret->video=1;
			}
		}
		else
		{
			$ret->video=-1;
		}
		
		// Album Photo
		$ret->photo=(int)$req->getPost("enable_photo");
		if ($ret->photo==1)
		{
			$privacy=(int)$req->getPost("photo_privacy");
			if ($privacy==0)
			{
				$ret->photo=0;
			}
			else
			{
				$ret->photo=1;
			}
		}
		else
		{
			$ret->photo=-1;
		}
		
		// Music
		$ret->music=(int)$req->getPost("enable_music");
		if ($ret->music==1)
		{
			$privacy=(int)$req->getPost("music_privacy");
			if ($privacy==0)
			{
				$ret->music=0;
			}
			else
			{
				$ret->music=1;
			}
		}
		else
		{
			$ret->music=-1;
		}
		
		// Blog
		$ret->blog=(int)$req->getPost("enable_blog");
		if ($ret->blog==1)
		{
			$privacy=(int)$req->getPost("blog_privacy");
			if ($privacy==0)
			{
				$ret->blog=0;
			}
			else
			{
				$ret->blog=1;
			}
		}
		else
		{
			$ret->blog=-1;
		}
		
		$ret->access=(int)$req->getPost("access");
		
		return $ret;
	}
	
	public function checkEventInfo(&$event){
		$err = array();
		if(empty($event))
			$err['all'] = 'Hãy điền đầy đủ thông tin vào các trường có dấu (<span style="color:red;">*</span>)';
		else{
			
			if ($event->event_name=="")
			{
				$err['event_name']="Bạn cần nhập tên sự kiện";
			}
			if ($event->description=="")
			{
				$err['description']="Bạn cần nhập mô tả sự kiện";
			}
			if ($event->network_id=="" || $event->network_id==0)
			{
				$err['network_id']="Bạn cần chọn một cộng đồng mà bạn đã tham gia";
			}
			if($event->cid=="" || $event->cid==0){
				$err['cid'] = 'Hãy lựa chọn chuyên mục cho sự kiện';
			}
			
			
			if ($event->email!="")
			{
				if (!ttCheckInput::checkEmail($event->email))
				{
					$err['email']="Email bạn điền không đúng định dạng";
				}
			}
			if ($event->website!="")
			{
				if (!ttCheckInput::checkWebsite($event->website))
				{
					$err['website']="Địa chỉ website bạn điền không đúng định dạng";
				}
			}
		    //va
           
            if($event->end_time < $event->start_time)
            {
                $err['start_time']="Thời gian kết thúc sự kiện phải xảy ra sau thời gian bắt đầu sự kiện";
            }
            if($event->end_time > $event->start_time + 12*30*24*60*60)
            {
                $err['end_time']="Thời gian diễn ra một sự kiện không kéo dài quá 1 năm";
            }
            if($event->end_time < time() && $event->eid == 0)
            {
                $err['end_time2']="Thời gian kết thúc 1 sự kiện không thể trong quá khứ";
            }
            //va
			
			
		}
		
		$event->event_name = check_plain(ttFormatText::stripTags($event->event_name));
		//$event->key_word = check_plain(ttFormatText::stripTags($event->key_word));
		//$event->short_cut = check_plain(ttFormatText::stripTags($event->short_cut));
		$event->slogan = check_plain(ttFormatText::stripTags($event->slogan));
		$event->email = check_plain(ttFormatText::stripTags($event->email));
		$event->phone = check_plain(ttFormatText::stripTags($event->phone));
		
		$event->website = check_plain(ttFormatText::stripTags($event->website));
		$event->address = check_plain(ttFormatText::stripTags($event->address));
		
		return $err;
	}
	
	public function checkEventEditPrivacy($eid){
		$eid = (int)$eid;
		$err = array();
		$user = $this->getUser();
		
		if($eid > 0){
			$event_old = $this->_helper->modelLoader->getEventInfo($eid);
			if(!$event_old){
				$err['chk_privacy'] = 'Không tồn tại sự kiện ứng với ID: '.$eid;
			}
			// chi co admin hoac nguoi tao moi co quyen sua
           // else if(!$this->_helper->modelLoader->isEventAdmin($eid, $user->uid)() ){
           //va
			else if(!$this->_helper->modelLoader->isEventAdmin($eid, $user->uid) && ! $this->isAdminEvent() ){
            //va
				$err['chk_privacy'] = 'Bạn không có quyền sửa sự kiện này';
			}
		}

		return $err;
	}
	
	public function makeDefaultEvent(){
		$event = new stdClass();
		
		$event->eid = 0;
		$timeStr = date('Y/m/d H:00:00');
		
		$event->start_time = strtotime($timeStr) + 3600;
		$event->end_time = strtotime($timeStr) + 24*60*60+3600;
		
		$event->network_id=0;
		$event->phone='';
		$event->key_word='';
		$event->slogan='';
		
		$event->short_cut='';
		$event->description='';
		$event->event_name='';
		$event->cid=0;
		$event->forum=0;
		$event->comment=0;
		$event->bookmark=0;
		$event->photo=0;
		$event->video=0;
		$event->music=0;
		$event->blog=0;
		$event->public=0;
		$event->access=0;
		$event->country=0;
		$event->city=0;
		$event->district=0;
		$event->address="";
		$event->email="";
		$event->website="";

		return $event;
	}
	
	public function saveEvent($event){
		$eventModel = $this->loadModel('Event');
		$user = $this->getUser();
		if(!$event->eid && (!isset($event->uid) || !$event->uid ))
			$event->uid = $user->uid;
		if(!$event->eid && (!isset($event->member_count) || !$event->member_count ))
			$event->member_count = 1;
		// status =1: insert new Event
		if(!$event->eid){  // cu~ if($event->eid) ??????????????
			$event->created = time();
		}
		$event->changed = time();
		
		$eidNew = $eventModel->save($event);
		if($eidNew != $event->eid){
			$totalEvent = $this->_helper->event->getUserEventCount($user->uid);
			$eventModel->updateStatistic($user->uid, $totalEvent);
			$memberModel = $this->loadModel('Member');
			$isAdmin = true;
			$memberModel->addNewMember($eidNew, $user->uid, $isAdmin);
			//$this->sendLog('event/add', $user->uid, $event->eid, $event->eid, $user->uid);
			$logevent = array(
	              'action'        =>  'event/create',
	              'uid'           =>  $user->uid,
	              'username'      =>  $user->name,
	              'eid'           =>  $eidNew,
	              'event_name'		=>  $event->event_name,
	              'created'       =>  time()
	          );
			ThriftLogger::thrift_log_get_content($logevent);
		}
		else{
			$logevent = array(
              'action'        =>  'event/edit',
              'uid'           =>  $user->uid,
              'username'      =>  $user->name,
              'eid'           =>  $event->eid,
              'event_name'    =>  $event->event_name,
              'event_logo'    =>  $event->logo,
              'old_event'		=>  $event, //Thông tin trước khi sửa
              'created'       =>  time()
			);
			ThriftLogger::thrift_log_get_content($logevent);
		}
		return $eidNew;
	}
	

	public function cancelAction(){
		$eid = (int)$this->_getParam('eid', 0);
		$user = $this->getUser();
		if(!$this->_helper->modelLoader->isEventAdmin($eid, $user->uid)){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event/detail/'.$eid);
		}
		
		
		$req = $this->getRequest();
		$err = array();
		if($req->isPost()){
			$msg = $req->getPost('messContent', "");
			if($msg==""){
				$err[] = "Hãy nhập vào nội dung thông báo";
			}
			else{
				// Prepare Insert to DB
		 		$sendId = $user->uid;
		 		$memberList = $this->_helper->modelLoader->getMemberList($eid);
	
		 		// --------------------
		 		if (is_array($memberList) && count($memberList)>0) {
		 			/*
			 		$messTitle = "Sự kiện bị huỷ bỏ";
			 		$isInvite = 0;
			 		$time = time();
			 		// Get status insert to DB -- return TRUE or FALSE
			 		$sendstatus = _mymessage_send_mail($sendId, $receiveIdArr, $time, $messTitle, $messContent);
			 		// Check if insert success
			 		if ($sendstatus) {
			 			$msg_success = "Thông báo của bạn được gửi thành công tới các khách tham gia trước khi sự kiện bị xoá!";
			 			$ok = 1;
			 			myttevent_delete($eid);
			 		}
			 		else {
			 			$err[] = "Có lỗi trong quá trình gửi";
			 			$ok = 0;
			 		}
					*/
		 		}
		 		$memberModel = $this->loadModel('Member');
		 		$memberModel->removeAllEventRequest($eid);
		 		$memberModel->removeAllEventMember($eid);
		 		$eventModel = $this->loadModel('Event');
		 		$eventModel->destroyEvent($eid);
		 		$event = $this->_helper->modelLoader->getEventInfo($eid);
		 		//$this->sendLog('event/del', $user->uid, $event->eid, $event->eid, $event->uid);
		 		$logevent = array(
		            'action'        =>  'event/delete',
		            'uid'         =>  $user->uid, //thông tin người xóa
		            'username'       =>  $user->name,            
		            'eid'           =>  $eid,
		            'event_name'  =>  $event->event_name,
		            'event'  => $event, //Thông tin của sự kiện dưới dạng object
		            'created'       =>  time()
		        );
		 		ThriftLogger::thrift_log_get_content($logevent);
		 		
		 		$event = $this->_helper->modelLoader->getEventInfo($eid, false, false);
		 		
		 		$this->view->message = "Sự kiện đã được huỷ bỏ thành công! Quay về <a href=\"/event\"><strong>trang chủ sự kiện</strong></a>";
		 		$this->_helper->layout->setLayout('event-edit');
				$this->render("alert");
				return ;
			}
		}
		$this->_helper->layout->setLayout('event-edit');
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$this->view->event = $event;
		$this->view->errors = $err;
	}
	
	
	public function detailAction(){
		
		$eid = $this->_getParam('eid');
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		if(empty($event) || $event->eid<=0)
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event');
			
		$user = $this->getUser();
		
		$isSecure = $this->_helper->privacy->isEventSecure($event->access);
		$isPulic = $this->_helper->privacy->isEventPublic($event->access);
		
		$isAdmin = $this->_helper->modelLoader->isEventAdmin($eid, $user->uid);
		$isMember = $this->_helper->modelLoader->isEventMember($eid, $user->uid);
		
		if ($isSecure && !$isMember && !$isAdmin){
			$this->_helper->getHelper('Redirector')->gotoUrlAndExit('/event');
		}
		$this->_helper->eventCommon->buildMainMenuBlock();
		$this->_helper->layout->setLayout('event-detail');
        $this->setTitle($event->event_name);
		
		$this->view->manageToolBlock = $this->htmlManageToolBlock($eid);
		$this->view->joinBlock = $this->htmlJoinBlock($eid);
		$this->view->adminBlock = $this->htmlAdminBlock($eid);
		$this->view->guestBlock = $this->htmlGuestBlock($eid);
		$this->view->hotBlock = $this->_helper->eventCommon->buildHtmlHotBlock();
		$this->view->sameCatBlock = $this->_helper->eventCommon->buildHtmlSameCatBlock($eid);
		$this->view->infoBlock = $this->htmlInfoBlock($eid);
		$this->view->memberBlock = $this->htmlMemberBlock($eid);
		
		$photoBolock = "";
		$videoBlock = "";
		$musicBlock = "";
		$blogBlock = "";
		$bookmarkBlock = "";
		$forumBlock = "";
		$commentBlock = "";
		
		if($isPulic || $isMember){
			if($isPulic = $this->_helper->privacy->isEnable('video', $event))
				$videoBlock = $this->htmlVideoBlock($eid);
            
			if($isPulic = $this->_helper->privacy->isEnable('photo', $event))
				$photoBolock = $this->htmlPhotoBlock($eid);
            
			if($isPulic = $this->_helper->privacy->isEnable('music', $event))
				$musicBlock = $this->htmlMusicBlock($eid);
            
			if($isPulic = $this->_helper->privacy->isEnable('blog', $event))
				$blogBlock = $this->htmlBlogBlock($eid);
			if($isPulic = $this->_helper->privacy->isEnable('bookmark', $event))
				$bookmarkBlock = $this->htmlBookmarkBlock($eid);
			if($isPulic = $this->_helper->privacy->isEnable('forum', $event))
				$forumBlock = $this->htmlForumBlock($eid);
			if($isPulic = $this->_helper->privacy->isEnable('comment', $event))
				$commentBlock = $this->htmlWallBlock($eid);
            
		}
        
		$this->view->photoBlock = $photoBolock;
		$this->view->videoBlock = $videoBlock;
		$this->view->musicBlock = $musicBlock;
		$this->view->blogBlock = $blogBlock;
		$this->view->bookmarkBlock = $bookmarkBlock;
		$this->view->forumBlock = $forumBlock;
		$this->view->commentBlock = $commentBlock;
	}
	
	
	public function htmlManageToolBlock($eid){
		$assign_list = array();
		$user = $this->getUser();
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$assign_list['event'] = $event;
		$assign_list['user'] = $user;
		$assign_list['isAdmin'] = $this->_helper->modelLoader->isEventAdmin($eid, $user->uid);
		$assign_list['isPublic'] = $this->_helper->privacy->isEventPublic($event->access);
		$assign_list['isPrivate'] = $this->_helper->privacy->isEventPrivate($event->access);
		$assign_list['isSecure'] = $this->_helper->privacy->isEventSecure($event->access);
		//va
        $assign_list['isPremium']= $this->_helper->privacy->isEventPremium($event->access);
        //va
		
		$memberStatus = $this->_helper->modelLoader->getMemberStatus($eid, $user->uid);
		$assign_list['memberStatus'] = $memberStatus;
		return $this->view->partial('event/manage-tool.phtml', $assign_list);
	}
	
	public function htmlJoinBlock($eid){
		
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$assign_list = array('eid'=>$eid);
		$assign_list['isPublic'] = $this->_helper->privacy->isEventPublic($event->access);
		$assign_list['isPrivate'] = $this->_helper->privacy->isEventPrivate($event->access);
		$assign_list['isSecure'] = $this->_helper->privacy->isEventSecure($event->access);
        //va
        $assign_list['isPremium']= $this->_helper->privacy->isEventPremium($event->access);
		//va
		
		$user = $this->getUser();
		$memberStatus = $this->_helper->modelLoader->getMemberStatus($eid, $user->uid);
		$assign_list['memberStatus'] = $memberStatus;
		
		return $this->view->partial('event/join-block.phtml', $assign_list);
	}

	public function htmlAdminBlock($eid){
		
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$assign_list = array();
		$assign_list['adminList'] = $this->_helper->modelLoader->getAdminList($eid);
		$assign_list['event'] = $event;
		
		return $this->view->partial('event/admin-block.phtml', $assign_list);
	}
	
	public function htmlGuestBlock($eid){
		
		$cache_key = "html_guest_block_".$eid;
		$data = $this->getCache($cache_key);
		if($data === false){
			$memberModel = $this->loadModel('Member');	
			
			$invited_list  = $memberModel->getGuestInvited($eid, EVENT_INVITE_REQUEST_SENT, 0, 3);
			$maybe_list  = $memberModel->getGuestInvited($eid, EVENT_INVITE_REQUEST_MAYBE_ATTENDING, 0, 6);
	
			
			$assign_list = array();
			$assign_list['invited_list'] = $invited_list;
			$assign_list['maybe_list'] = $maybe_list;
			$assign_list['eid'] = $eid;
			$data = $this->view->partial('event/guest-block.phtml', $assign_list);
			$this->setCache($cache_key, $data);
		}
		return $data;
	}
	
	public function htmlMemberBlock($eid){
		$assign_list = array();
		$user = $this->getUser();
		$assign_list['memberStatus'] = $this->_helper->modelLoader->getMemberStatus($eid, $user->uid);
		$assign_list['member_list'] = $this->_helper->modelLoader->getMemberList($eid);
		$assign_list['event'] = $this->_helper->modelLoader->getEventInfo($eid);
		
		return $this->view->partial('event/member-block.phtml', $assign_list);
	}
	
	public function htmlPhotoBlock($eid){
        return "";
		$cacheKey = "html_event_photo_block_".$eid;
		$data = $this->getCache($cacheKey);
		
		if(!$data){
			$v_client = null;
			$photos = array();
			$totalEventPhoto = 0;
			
			try {
				$v_client = new PhotoService(PHOTO_THRIFT_SERVER, PHOTO_THRIFT_PORT);
				$v_client->OpenTransport();
				$photos = $v_client->client()->getEventAlbum($eid, 1, 3);
				$totalEventPhoto = $v_client->client()->getEventAlbumCount($eid);
				
				$v_client->CloseTransport();
			} catch (Exception $ex){
				//$photos = array();
			}
			$user = $this->getUser();
			$array_list = array(
					'photos'=>$photos, 
					'totalEventPhoto'=>$totalEventPhoto, 
					'eid'=>$eid,
					'isCanAdd'=>$this->_helper->privacy->isCanAdd('photo', $eid, $user->uid));
		    $data = $this->view->partial('event/photo-block.phtml', $array_list);
		    $this->setCache($cacheKey, $data);
		}
		return $data;
	}
	
	public function htmlVideoBlock($eid){
		$cacheKey = "html_event_video_block_".$eid;
		$data = $this->getCache($cacheKey);
		if(!$data){
			$v_client = null;
			$videos = array();
			$totalEventVideo = 0;
			
			try {
				$v_client = new VideoService(VIDEO_THRIFT_SERVER, VIDEO_THRIFT_PORT);
				$v_client->OpenTransport();
				$videos = $v_client->client()->getEventVideo($eid, 1, 3);
				$totalEventVideo = $v_client->client()->getEventVideoCount($eid);
				
				$v_client->CloseTransport();
			} catch (Exception $ex){
				//$videos = array();
			}
			$user = $this->getUser();
			$array_list = array(
					'videos'=>$videos, 
					'totalEventVideo'=>$totalEventVideo, 
					'eid'=>$eid,
					'isCanAdd'=>$this->_helper->privacy->isCanAdd('video', $eid, $user->uid));
		    $data = $this->view->partial('event/video-block.phtml', $array_list);
		    $this->setCache($cacheKey, $data);
		}
		return $data;
	}
	
	public function htmlMusicBlock($eid){
		$eid = (int)$eid;
		$cacheKey = "html_event_music_block_".$eid;
		$data = $this->getCache($cacheKey);
		if(!$data){
			$m_client = null;
			$musics = array();
			$totalEventMusic = 0;
			
			try {
				$m_client = new MusicService(MUSIC_THRIFT_SERVER, MUSIC_THRIFT_PORT);
				$m_client->OpenTransport();
				$musics = $m_client->client()->getEventMusic($eid, 1, 3);
				$totalEventMusic = $m_client->client()->getEventMusicCount($eid);
				
				$m_client->CloseTransport();
			} catch (Exception $ex){
				//var_dump($ex);exit();
			}
			$user = $this->getUser();
			$array_list = array(
					'musics'=>$musics, 
					'totalEventMusic'=>$totalEventMusic, 
					'eid'=>$eid,
					'isCanAdd'=>$this->_helper->privacy->isCanAdd('music', $eid, $user->uid));
		    $data = $this->view->partial('event/music-block.phtml', $array_list);
		    $this->setCache($cacheKey, $data);
		}
		return $data;
	}
	
	public function htmlBlogBlock($eid){
        return "";
		$eid = (int)$eid;
		$cacheKey = "html_event_blog_block_".$eid;
		$data = $this->getCache($cacheKey);
		if(!$data){
			$blogs = array();
			$totalEventBlog = 0;
			
			try {
				$m_client = new BlogService(BLOG_THRIFT_SERVER, BLOG_THRIFT_PORT);
				$m_client->OpenTransport();
				$blogs = $m_client->client()->getEventBlog($eid, 1, 5);
				$totalEventBlog = $m_client->client()->getEventBlogCount($eid);
				
				$m_client->CloseTransport();
			} catch (Exception $ex){
				//var_dump($ex);exit();
			}
			
			$user = $this->getUser();
			$array_list = array(
					'blogs'=>$blogs, 
					'totalEventBlog'=>$totalEventBlog, 
					'eid'=>$eid,
					'isCanAdd'=>$this->_helper->privacy->isCanAdd('blog', $eid, $user->uid));
		    $data = $this->view->partial('event/blog-block.phtml', $array_list);
		    $this->setCache($cacheKey, $data);
		}
		return $data;
	}
	
	public function htmlBookmarkBlock($eid){
		
		$cacheKey = "html_event_bookmark_block_".$eid;
		$data = $this->getCache($cacheKey);
		if(!$data){
			$bookmarkList = $this->_helper->bookmark->getEventBookmarks($eid, 1, 5);
			$total = $this->_helper->bookmark->getEventBookmarkCount($eid);
			$user = $this->getUser();
			
			$assign_list = array(
							'bookmarkList'=>$bookmarkList, 
							'total'=>$total, 'eid'=>$eid,
							'isCanAdd'=>$this->_helper->privacy->isCanAdd('bookmark', $eid, $user->uid));
			
			$data = $this->view->partial('event/bookmark-block.phtml', $assign_list);
			$this->setCache($cacheKey, $data);
		}
		return $data;
	}
	
	public function htmlForumBlock($eid){
		$user = $this->getUser();
		$data = $this->_helper->Forum->getEventBookmarkTopics($eid, 5, true); 
		$data['eid'] = $eid;
		$data['isCanAdd'] = $this->_helper->privacy->isCanAdd('forum', $eid, $user->uid);
		
		return $this->view->partial('event/forum-block.phtml', $data);
	}
	
	public function htmlWallBlock($eid){
		
		$assign_list = array();
		$user = $this->getUser();
		$assign_list['event'] = $this->_helper->modelLoader->getEventInfo($eid);
		$assign_list['user'] = $user;
		$assign_list['isCanAdd'] = $this->_helper->privacy->isCanAdd('comment', $eid, $user->uid);
		
		return $this->view->partial('event/comment-block.phtml', $assign_list);
	}
	
	
	public function htmlInfoBlock($eid){
		$event = $this->_helper->modelLoader->getEventInfo($eid);
		$user = $this->getUser();
		$data['event'] = $event;
		$data['isAdmin'] = $this->_helper->modelLoader->isEventAdmin($eid, $user->uid);
		return $this->view->partial('event/info.phtml', $data);
	}
	
	private function tmpBlogs(){
		$ret = array();
		
		$blog = new stdClass();
		$blog->nid = 110963;
		$blog->uid = 448;
		$blog->uname = 'sonlecong';
		$blog->title = 'Test blog của Hưng Nguyễn';
		$blog->teaser = "Test blog của Hưng NguyễnTest blog của Hưng NguyễnTest blog của Hưng Nguyễn";
		$blog->body = 'Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn Test blog của Hưng Nguyễn ';
		$blog->status = 1;
		$blog->created = 1216805262;
		$blog->comment = 1;
		$blog->last_comment_timestamp = 1216807999;
		$blog->last_comment_name = 'haict';
		$blog->last_comment_uid = 58254;
		$blog->comment_count = 100;
		$blog->link_id = 0;
		
		for($i=0; $i<20;$i++){
			$blog->nid = $blog->nid+$i;
			$ret[] = $blog;
		}
	
		return $ret;
	} 
}